package org.example.optimistic.lock.ATM;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhengdp
 * @Description
 * @Date 2022/11/19 15:46
 * @Created by zhengdp
 */
public interface Account {

    // 获取余额
    Integer getBalance();

    // 取款
    void withdraw(Integer amount);

    /**
     * 方法内启动1000个线程，每个线程做 -10元的操作
     * 如果初始余额为 10000，那么正确的结果应该是0
     * @param account
     */
    static void demo(Account account) {
        List<Thread> ts = new ArrayList<>();
        for( int i =0 ; i< 1000; i++) {
            ts.add(new Thread( () -> {
                account.withdraw(10);
            }));
        }
        long start = System.nanoTime();
        ts.forEach(Thread::start);
        ts.forEach(t -> {
            try {
                // 等待线程执行结束
                t.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        long end = System.nanoTime();
        System.out.println(account.getBalance() + " cost: " + (end-start)/1000_000 + " ms");
    }

}
